<template>
  <div class="wrapper default-form-detail-wrapper">
    <div class="default-form-detail-header">
      <div v-show="isShowSelectWrapper(pageAction)" style="flex: 1;">
        <el-button @click="submitFlowForm" icon="Promotion" round type="primary"
                   v-show="isShowSubmitButton(pageAction)">
          发送
        </el-button>
        <el-button icon="Collection" style="margin-left: 10px" @click="save" round v-show="isShowSaveButton(pageAction)">保存待发</el-button>

        <div class="flow-select-row" style="margin-top:15px;">
          <div class="flow-select-title">标题:</div>
          <div class="flow-select-body" v-if="selectedFlow && selectedFlow.titleFormula">
            <el-input readonly v-model="selectedFlow.titleFormula.formulaTitle"/>
          </div>
        </div>

        <div class="flow-select-row">
          <div class="flow-select-title">流程:</div>
          <div class="flow-select-body">
            <el-select v-model="selectedFlowKey" style="flex: 1;" placeholder="流程" @change="selectedFlowKeyChange">
              <el-option v-for="item in flows" :key="item.id" :label="item.name" :value="item.id"/>
            </el-select>
            <el-button style="margin-left: 10px" @click="showSelectedFlow" round>查看流程</el-button>
          </div>
        </div>
      </div>
      <div v-show="pageAction === 'approve'">
        <div class="flow-title">标题: {{ processInstance.processTitle }}</div>
        <div class="flow-info">发起人: {{ processInstance.applyByName }} <span
            style="margin-left: 10px">发起时间: {{ processInstance.createTime }}</span></div>
        <div class="flow-info">相关附件:</div>
        <div></div>
      </div>

      <div v-show="pageAction === 'detail'">
        <div class="flow-title">标题: {{ processInstance.processTitle }}</div>
        <div class="flow-info">发起人: {{ processInstance.applyByName }} <span
          style="margin-left: 10px">发起时间: {{ processInstance.createTime }}</span></div>
        <div class="flow-info">相关附件:</div>
        <div></div>
      </div>
    </div>


    <el-scrollbar class="default-form-detail-body">
      <DefaultFormRender :pageAction="pageAction" ref="DefaultFormRender"
                         :view="view" :formDefinition="formDefinition" :components="components"/>
    </el-scrollbar>
    <FlowPreviewModal ref="FlowPreviewModal"/>
  </div>
</template>

<script>
import {getAction, postAction} from '@/request/BaseRequest';
import {DefaultViewDefinition} from '@/components/form/DefaultFormDefinition';
import {guid, isEmpty} from '@/utils/CommonUtils';
import {Promotion} from '@element-plus/icons-vue';
import FlowPreviewModal from '@/components/flow/FlowPreviewModal';
import DefaultFormRender from '@/components/platwork/FormDetailComponent/DefaultFormDetailComponent/DefaultFormRender';
import {shallowRef} from 'vue';
import {DefaultFormula} from '@/components/form/DefaultFormDefinition';

export default {
  name: 'DefaultFormDetailComponent',
  components: {
    DefaultFormRender,
    FlowPreviewModal
  },
  data() {
    return {
      Promotion: shallowRef(Promotion),
      contentId: guid(),
      view: JSON.parse(JSON.stringify(DefaultViewDefinition)),
      components: [],
      formDefinition: {
        form: {},
        formFields: [],
        subForms: []
      },
      flows: [],
      selectedFlowKey: undefined,
      selectedFlow: {
        name: '流程',
        id: 'ss',
        titleFormula: DefaultFormula,
      },
      userTask: {
        id: undefined,
        taskName: undefined,
        processInstanceId: undefined
      },
      processInstance: {
        processTitle: undefined,
        applyBy: undefined,
        applyByName: undefined,
        createTime: undefined,
      },
      pageAction: 'edit' //edit, detail, approve, add
    };
  },
  mounted() {
    this.pageAction = this.$route.query.action;
    this.loadView();
  },
  methods: {
    isShowSubmitButton(pageAction) {
      if (pageAction === 'add') return true;
      if (pageAction === 'edit') return true;
      return false;
    },
    selectedFlowKeyChange() {
      let index = this.flows.findIndex(f => f.id === this.selectedFlowKey);
      if (index !== -1) {
        this.selectedFlow = this.flows[index];
      }
    },
    isShowSelectWrapper(pageAction) {
      if (pageAction === 'add') return true;
      if (pageAction === 'edit') return true;
      return false;
    },
    isShowSaveButton(pageAction) {
      if (pageAction === 'add') return true;
      if (pageAction === 'edit') return true;
      return false;

    },
    computeEditable() {
      if (this.pageAction === 'add') return true;
      if (this.pageAction === 'edit') return true;
      return false;
    },
    loadView() {
      this.loading = true;
      getAction('/plat/platFormViewPublish/queryById', {id: this.$route.query.viewId}).then(data => {
        if (data.success) {
          this.setViewDefinition(data.result);
        } else {
          this.$notification.error({message: data.message, duration: 3});
        }
        this.loading = false;
      })

      if (this.pageAction === 'approve') {
        this.loadApproveData();
      }
    },
    loadApproveData() {
      this.loading = true;
      getAction('/flow/loadUserTaskById', {userTaskId: this.$route.query.userTaskId}).then(data => {
        if (data.success) {
          this.userTask = data.result;
          this.loadProcessInstance();
        } else {
          this.$notification.error({message: data.message, result: data.result, duration: 3});
        }
        this.loading = false;
      })
    },
    loadProcessInstance() {
      this.loading = true;
      getAction('/flow/loadProcessInstanceId', {processInstanceId: this.userTask.processInstanceId}).then(data => {
        if (data.success) {
          this.processInstance = data.result;
        } else {
          this.$notification.error({message: data.message, result: data.result, duration: 3});
        }
        this.loading = false;
      })
    },
    setViewDefinition(data) {
      data.viewDefinition = JSON.parse(data.viewDefinition);
      this.view = data;
      this.components = this.view.viewDefinition.children;
      this.loadFormDefinition(() => {
        this.resolvePageAction();
        this.$nextTick(() => {
          this.loadFormData();
        });
      });
    },
    setFormData(formData) {
      this.$refs.DefaultFormRender.setFormData(formData);
    },
    loadFormData() {
      if (this.pageAction === 'add') return;
      this.loading = true;
      getAction('/plat/queryById', {id: this.$route.query.dataId, formId: this.formDefinition.form.id}).then(data => {
        if (data.success) {
          this.setFormData(data.result);
        } else {
          this.$notification.error({message: data.message, result: data.result, duration: 3});
        }
        this.loading = false;
      })
    },
    loadFormDefinition(callback) {
      this.loading = true;
      getAction('/plat/loadPublishedFormDefinition', {id: this.view.formId}).then(data => {
        if (data.success) {
          this.setFormDefinition(data.result);
          callback();
        } else {
          this.$notification.error({message: data.message, duration: 3});
        }
        this.loading = false;
      })
    },
    save() {
      // let data = this.getSubmitData();
      let data = this.$refs.DefaultFormRender.getData();
      data.formId = this.formDefinition.form.id;
      data.viewId = this.$route.query.viewId;
      data.tableName = this.formDefinition.form.tableName;
      data.id = this.$route.query.dataId;

      this.loading = true;
      postAction('/plat/update', data).then(data => {
        if (data.success) {
          this.$message.success('成功!');
          this.$windowManager.close();
        } else {
          this.$notification.error({message: data.message, result: data.result, duration: 3});
        }
        this.loading = false;
      })
    },
    submitFlowForm() {
      // let data = this.getSubmitData();
      let data = this.$refs.DefaultFormRender.getData();
      data.formId = this.formDefinition.form.id;
      data.viewId = this.$route.query.viewId;
      data.tableName = this.formDefinition.form.tableName;
      data.id = this.$route.query.dataId;
      data.selectedFlow = this.selectedFlow;

      this.loading = true;
      postAction('/plat/submit', data).then(data => {
        if (data.success) {
          this.$message.success('成功!');
          this.$windowManager.close();
        } else {
          this.$notification.error({message: data.message, result: data.result, duration: 3});
        }
        this.loading = false;
      })
    },
    setFormDefinition(formDefinition) {
      if (isEmpty(formDefinition)) return;
      this.formDefinition.form = formDefinition.form;
      this.formDefinition.formFields = formDefinition.formFields;
      this.formDefinition.subForms = formDefinition.subForms;
      this.formDefinition.formRelationVos = formDefinition.formRelationVos;

      this.$refs.DefaultFormRender.setFormDefinition(this.formDefinition);
      this.loadFlowDefinitionsByFormDefinition();
    },
    loadFlowDefinitionsByFormDefinition() {
      let data = {formId: this.formDefinition.form.id};
      this.loading = true;
      getAction('/flow/loadFlowDefinitionsByFormDefinition', data).then(data => {
        if (data.success) {
          this.setFlows(data.result);
        } else {
          this.$notification.error({message: data.message, result: data.result, duration: 3});
        }
        this.loading = false;
      })
    },
    setFlows(flows) {
      this.flows = flows;
      if (flows && flows.length >= 1) {
        this.selectedFlowKey = flows[0].id;
        this.selectedFlow = flows[0];
      }
    },
    showSelectedFlow() {
      this.$refs.FlowPreviewModal.setData({id: this.selectedFlowKey});
    },
    resolvePageAction() {
      let methodName = `${this.pageAction}`;
      this[methodName]();
    },
    edit() {

    },
    detail() {

    },
    approve() {

    },
    add() {
      this.resetFields();
    },
    resetFields() {
    },

  }
};
</script>

<style scoped>
table {
  border-collapse: collapse;
}

.wrapper {
  background: #8f8f8f;
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 100%;
  height: 100%;
}

table td {
  border: 1px solid #343a40;
}

.default-form-detail-header {
  position: sticky;
  top: 0;
  width: 100%;
  left: 0;
  background: white;
  padding: 5px 15px 15px 15px;
  box-sizing: border-box;
  display: flex;
  box-shadow: var(--el-box-shadow);
  z-index: 1;
}

.flow-select-wrapper {
  margin-top: 15px;
}

.flow-select-row {
  display: flex;
  align-items: center;
  margin-top: 10px;
}

.flow-select-title {
  width: 40px;
  text-align: right;
  padding-right: 10px;
}

.flow-select-body {
  flex: 1;
  display: flex;
  align-items: center;
}

.flow-title {
  font-size: 20px;
  font-weight: bold;
}

.flow-info {
  color: #909399;
  margin-top: 5px;
  font-size: 12px;
}
</style>
<style>
.default-form-detail-body .el-scrollbar__view {
  display: flex;
  justify-content: center;
  width: 100vw;
}
</style>
